<template>
    <div>
        <button @click="startRecording" v-if="!isRecording">开始录音</button>
        <button @click="stopRecording" v-if="isRecording">停止录音</button>
        <audio ref="audioPlayer" controls></audio>
    </div>
</template>

<script>
export default {
    data() {
        return {
            isRecording: false,
            mediaRecorder: null,
            audioChunks: [],
            audioURL: null,
        }
    },
    methods: {
        startRecording() {
            wx.ready(() => {
                wx.startRecord({
                    success: () => {
                        this.isRecording = true
                    },
                    cancel: () => {
                        alert('用户拒绝授权录音')
                    },
                })
            })
        },
        stopRecording() {
            wx.stopRecord({
                success: () => {
                    wx.onVoiceRecordEnd({
                        complete: (res) => {
                            this.audioChunks.push(res.localId)
                            this.isRecording = false
                        },
                    })
                },
            })
        },
        playAudio() {
            if (this.audioChunks.length > 0) {
                wx.playVoice({
                    localId: this.audioChunks[this.audioChunks.length - 1],
                })
            } else {
                alert('没有录音文件')
            }
        },
    },
    mounted() {
        wx.config({
            // 配置微信JS-SDK
            debug: false,
            appId: '你的appId',
            timestamp: '', // 必填，生成签名的时间戳
            nonceStr: '', // 必填，生成签名的随机串
            signature: '', // 必填，签名，见附录1
            jsApiList: ['startRecord', 'stopRecord', 'onVoiceRecordEnd', 'playVoice'], // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
        })

        // 注册error回调函数
        wx.error(function (res) {
            console.log('微信JS-SDK配置错误', res)
        })
    },
}
</script>
